package com.shop.util;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.BeanUtilsBean;

import javax.servlet.http.Cookie;
import java.util.Map;

public class WebUtils {

    /**
     * 将字符串解析成int类型
     * @param strInt    字符串
     * @param defaultValue  默认值
     * @return
     */
    public static int parseInt(String strInt,int defaultValue){
        try {
            return Integer.parseInt(strInt);
        } catch (Exception e){
            return defaultValue;
        }

    }

    /**
     * 自动封装
     * @param bean  封装的bean对象
     * @param map   属性集合
     * @param <T>   封装的对象类型
     * @return      完成封装的对象
     */
    public static <T> T getBean(T bean,Map map){
        BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0);
        try {
            BeanUtils.populate(bean,map);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return bean;
    }

    /**
     * 查找指定名称的cookie
     * @param cookieName
     * @param cookies
     * @return
     */
    public static Cookie findCookie(String cookieName,Cookie[] cookies){
        if(cookieName==null||cookies==null||cookies.length==0){
            return null;
        }
        for(Cookie c:cookies){
            if (cookieName.equals(c.getName())){
                return c;
            }
        }
        return null;
    }

}
